import math
import random

import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
    """一个对飞船发射的子弹进行管理的类"""

    def __init__(self, ai_settings, screen, ship):
        """在飞船所处的位置创建一个子弹对象"""
        super(Bullet, self).__init__()
        self.screen = screen
        self.bullet_width = ai_settings.bullet_width
        self.image = pygame.Surface((ai_settings.bullet_width, ai_settings.bullet_height), pygame.SRCALPHA)

        # 在（0，0）处创建一个表示子弹的矩形，再设置正确的位置
        pygame.draw.rect(self.image, ai_settings.bullet_color, (0, 0, ai_settings.bullet_width,
                              ai_settings.bullet_height))
        self.rect = self.image.get_rect()
        # 使子弹再飞船中心头部生成
        self.rect.centerx = ship.rect.centerx
        self.rect.top = ship.rect.top

        # 创建拖尾特效
        self.trail_positions = []   # 储存轨迹点
        self.trail_length = 50      # 拖尾长度

        # 储存用小数表示的子弹位置
        self.y = float(self.rect.y)

        self.color = ai_settings.bullet_color
        self.speed_factor = ai_settings.bullet_speed_factor

    def update(self):
        """向上移动子弹"""
        # 更新表示子弹位置的小数值(向上移动)
        self.y -= self.speed_factor
        # 更新表示子弹的rect的位置
        self.rect.y = self.y
        # 记录轨迹点
        # 如果拖尾点数超过 trail_length，移除最旧的拖尾点（保持固定长度）。
        self.trail_positions.append((self.rect.centerx, self.rect.centery))
        if len(self.trail_positions) > self.trail_length:
            self.trail_positions.pop(0)

    def draw_bullet(self):
        """在屏幕上绘制子弹"""
        pygame.draw.rect(self.screen, self.color, self.rect)

    def draw_trail(self, surface):
        """绘制拖尾"""
        for i, pos in enumerate(self.trail_positions):
            alpha = int(255 * (i / len(self.trail_positions)))  # 透明度渐变：越旧的拖尾点越透明（alpha 值越小）
            radius = max(1, int(self.bullet_width * (i / len(self.trail_positions))))   # 大小渐变：越旧的拖尾点越小（radius 越小）
            trail_surf = pygame.Surface((radius * 2, radius * 2),pygame.SRCALPHA)   # 在 Surface 上绘制一个带透明度的圆形
            pygame.draw.circle(trail_surf, (*self.color, alpha), (radius, radius), radius)
            surface.blit(trail_surf, (pos[0]-radius, pos[1]-radius))


class EnemyBullet(Sprite):
    """敌军子弹类"""
    def __init__(self, aisettings, screen, x, y, target_x=None, target_y=None):
        super().__init__()
        self.aisettings = aisettings
        self.screen = screen

        # 创建图像表面
        self.image = pygame.Surface((aisettings.enemy_bullet_width,
                                     aisettings.enemy_bullet_height))
        self.image.fill(aisettings.enemy_bullet_color)  # 填充颜色

        # 创建子弹矩形
        self.rect = pygame.Rect(0, 0, aisettings.enemy_bullet_width, aisettings.enemy_bullet_height)
        self.rect.centerx = x
        self.rect.top = y

        # 储存子弹位置(浮点数)
        self.y = float(y)
        self.x = float(x)

        # 计算方向向量（指向玩家）
        dx = (target_x - x) + random.uniform(-50, 50)   # +-50像素误差
        dy = (target_y - y) + random.uniform(-50, 50)
        distance = max(1, int(math.sqrt(dx ** 2 + dy ** 2)))     # 避免除以0
        self.dx = dx / distance     # 单位向量 x
        self.dy = dy / distance     # 单位向量 y

        # 子弹的颜色和速度
        self.color = aisettings.enemy_bullet_color
        self.speed = aisettings.enemy_bullet_speed_factor

    def update(self):
        """更新子弹位置"""
        self.x += self.dx * self.speed
        self.y += self.dy * self.speed
        self.rect.x = self.x
        self.rect.y = self.y

    def draw_bullet(self):
        """绘制子弹"""
        pygame.draw.rect(self.screen, self.color, self.rect)



